package cn.ryh.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * NIO 客户端示例，
 * 测试时，先启动NioServerDemo，然后再启动NioClientDemo
 *
 * @author Raoyh
 * @Description
 * @create 2022-09-09 14:33
 */
public class NioClientDemo {
    public static void main(String[] args) throws IOException {
        client();
    }

    public static void client() throws IOException {
        //得到一个网络通道
        try (SocketChannel socketChannel = SocketChannel.open()) {
            //切换为非阻塞模式
            socketChannel.configureBlocking(false);
            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
            //连接服务器
            if (!socketChannel.connect(address)) {
                while (!socketChannel.finishConnect()) {
                    System.out.println("因为连接需要时间，客户端不会阻塞，可以做其它工作..");
                }
            }
            System.out.println("请输入需要发送的消息:");
            Scanner scan = new Scanner(System.in);
            while (scan.hasNext()) {
                String str = scan.next();
                //Wraps a byte array into a buffer
                ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
                socketChannel.write(buffer);
            }
        }
    }

}
